<template>
  <view class="container">
    <CarInfo :info="carInfo">
      <ve-cell-val label="保险单关联门店" :value="carInfo.siteName" />
      <ve-cell-val label="保险状态" :value="carInfo.insureStatusStr" />
    </CarInfo>
    <ve-form ref="veFormRef" :model="form" :rules="rules">
      <ve-card title="退保信息" type="none" fold v-model:initFold="foldStatus.fold1">
        <ve-form-item label="退保时间" prop="backDate" required>
          <ve-date-picker v-model="form.backDate" mode="date"></ve-date-picker>
        </ve-form-item>
        <ve-form-item label="退保金额" unit="元" :borderBottom="false">
          <ve-input-number :precision="2" placeholder="请输入" v-model="form.backAmount" />
        </ve-form-item>
      </ve-card>
    </ve-form>
    <ve-bottom-box>
      <ve-button type="primary" :loading="okLoading" @click="onSubmit">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { onLoad } from '@dcloudio/uni-app'
  import { ref } from 'vue'
  import { getDetailApi, refundInsureApi } from '@/api/asset/car-insure'
  import useFormFold from '@/hooks/useFormFold'
  import CarInfo from '@/pages/common/components/car-info.vue'

  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['backDate'],
    },
  ])
  const rules = ref({
    backDate: {
      required: true,
      message: '请选择退保时间',
    },
  })

  const carInfo = ref({})
  const form = ref({})
  onLoad((options) => {
    form.value.id = options.id
    // 获取保险详情
    getDetailApi({ id: form.value.id }).then((res) => {
      carInfo.value = res.result
    })
  })

  const veFormRef = ref(null)
  const okLoading = ref(false)
  const onSubmit = () => {
    veFormRef.value.validate((valid, errors) => {
      if (valid) {
        okLoading.value = true
        refundInsureApi(form.value)
          .then((res) => {
            uni.showToast({
              icon: 'none',
              title: res.message,
            })
            uni.navigateBack()
            // 刷新页面
            uni.$emit('carInsure_getList')
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors)
      }
    })
  }
</script>

<style lang="scss" scoped>
  .container {
    background: #f7f8fa;
    padding: 24rpx;
  }
</style>
